#include "head.h"
#include "config.h"
#include "cJSON.h"
#include "log.h"
#include "tcp.h"
#include "mysql.h"
#include "threadpool.h"
#include "epoll.h"
#include "taskqueue.h"
#include "msg.h"

/* Useage:  */

int main(int argc,char*argv[]){
    //初始化服务器
    int socket_fd = tcpInit();
    //连接数据库
    MYSQL* mysql;
    int conn = connMySQL(mysql);
    //初始化线程池
    status_t thread_pool;
    threadPoolInit(&thread_pool, THREAD_NUM);
    //初始化epoll，监听socket_fd
    int epoll_fd = epoll_create(1);
    ERROR_CHECK(epoll_fd, -1, "epoll_create");
    epollAddReadEvent(epoll_fd, socket_fd);
    
    while(1){
        struct epoll_event list[100];           //最大连接数100
        int epoll_num = epoll_wait(epoll_fd, list, 100, -1);

        for(int i = 0; i < epoll_num; i++){
            int fd = list[i].data.fd;
            //有新连接
            if(fd == socket_fd){
                int net_fd = accept(socket_fd, NULL, NULL);
                epollAddReadEvent(epoll_fd, net_fd);
            }
            //有客户发信息过来
            else{
                CmdType type;
                char data[BUF_SIZE] = {0};
                recvMsg(fd, &type, data);
                taskEnQueue(&thread_pool.queue, fd, type, data);
            }
        }
    }

    close(socket_fd);
    close(epoll_fd);

    return 0;
}

